package com.jn.zhinongbao.adapter.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

import com.example.supportingagriculturaltreasures.NewsDetailActivity;
import com.example.supportingagriculturaltreasures.PublishNewsActivity;
import com.example.supportingagriculturaltreasures.R;
import com.example.supportingagriculturaltreasures.adapter.NewsAdapter;
import com.example.supportingagriculturaltreasures.bean.News;
import com.example.supportingagriculturaltreasures.database.DatabaseHelper;
import com.example.supportingagriculturaltreasures.utils.PreferenceManager;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.google.android.material.tabs.TabLayout;

import java.util.List;

public class AgricultureFragment extends Fragment implements NewsAdapter.OnNewsClickListener {
    
    private RecyclerView recyclerView;
    private SwipeRefreshLayout swipeRefreshLayout;
    private TabLayout tabLayout;
    private FloatingActionButton fabPublish;
    
    private NewsAdapter newsAdapter;
    private DatabaseHelper databaseHelper;
    private PreferenceManager preferenceManager;
    private List<News> newsList;

    public static AgricultureFragment newInstance() {
        return new AgricultureFragment();
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_agriculture, container, false);
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        
        initViews(view);
        initData();
        setupRecyclerView();
        setupTabLayout();
        setupClickListeners();
        loadNews();
    }

    private void initViews(View view) {
        recyclerView = view.findViewById(R.id.recycler_view);
        swipeRefreshLayout = view.findViewById(R.id.swipe_refresh_layout);
        tabLayout = view.findViewById(R.id.tab_layout);
        fabPublish = view.findViewById(R.id.fab_publish);
    }

    private void initData() {
        databaseHelper = new DatabaseHelper(getContext());
        preferenceManager = new PreferenceManager(getContext());
    }

    private void setupRecyclerView() {
        recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
        newsAdapter = new NewsAdapter(this);
        recyclerView.setAdapter(newsAdapter);
        
        swipeRefreshLayout.setOnRefreshListener(this::loadNews);
        swipeRefreshLayout.setColorSchemeResources(
            android.R.color.holo_blue_bright,
            android.R.color.holo_green_light,
            android.R.color.holo_orange_light,
            android.R.color.holo_red_light
        );
    }

    private void setupTabLayout() {
        tabLayout.addTab(tabLayout.newTab().setText("全部"));
        tabLayout.addTab(tabLayout.newTab().setText("种植技术"));
        tabLayout.addTab(tabLayout.newTab().setText("养殖技术"));
        tabLayout.addTab(tabLayout.newTab().setText("农业资讯"));
        tabLayout.addTab(tabLayout.newTab().setText("病虫防治"));
        
        tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                filterNewsByCategory(tab.getPosition());
            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {}

            @Override
            public void onTabReselected(TabLayout.Tab tab) {}
        });
    }

    private void setupClickListeners() {
        fabPublish.setOnClickListener(v -> {
            if (preferenceManager.getCurrentUserId() != -1) {
                Intent intent = new Intent(getContext(), PublishNewsActivity.class);
                startActivity(intent);
            } else {
                Toast.makeText(getContext(), "请先登录", Toast.LENGTH_SHORT).show();
            }
        });
    }

    private void loadNews() {
        swipeRefreshLayout.setRefreshing(true);
        
        try {
            newsList = databaseHelper.getAllNews();
            newsAdapter.updateNews(newsList);
        } catch (Exception e) {
            e.printStackTrace();
            Toast.makeText(getContext(), "加载新闻失败", Toast.LENGTH_SHORT).show();
        } finally {
            swipeRefreshLayout.setRefreshing(false);
        }
    }

    private void filterNewsByCategory(int position) {
        if (newsList == null) return;
        
        String category = getCategoryByPosition(position);
        List<News> filteredNews;
        
        if (position == 0) { // 全部
            filteredNews = newsList;
        } else {
            filteredNews = databaseHelper.getNewsByCategory(category);
        }
        
        newsAdapter.updateNews(filteredNews);
    }

    private String getCategoryByPosition(int position) {
        switch (position) {
            case 1: return "种植技术";
            case 2: return "养殖技术";
            case 3: return "农业资讯";
            case 4: return "病虫防治";
            default: return "";
        }
    }

    @Override
    public void onNewsClick(News news) {
        // 增加阅读量
        databaseHelper.incrementNewsViewCount(news.getId());
        
        // 跳转到新闻详情页
        Intent intent = new Intent(getContext(), NewsDetailActivity.class);
        intent.putExtra("news", news);
        startActivity(intent);
    }

    @Override
    public void onResume() {
        super.onResume();
        loadNews(); // 重新加载数据
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (databaseHelper != null) {
            databaseHelper.close();
        }
    }
} 